<?php

namespace humhub\modules\api\controllers;

use Yii;
use humhub\components\Controller;
use humhub\modules\space\models\Space;
use humhub\modules\user\models\User;
use humhub\models\Setting;
use humhub\modules\space\widgets\Image;
use humhub\modules\content\components\ContentActiveRecord;
use humhub\modules\content\components\ContentContainerActiveRecord;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 搜索用户, Space板块, 和内容
 */
class SearchController extends Base4Controller
{

    const SCOPE_ALL = "all";
    const SCOPE_USER = "user";
    const SCOPE_SPACE = "space";
    const SCOPE_CONTENT = "content";

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
            'guestAllowedActions' => ['index']
        ];

        return $behaviors;
    }

    /**
     * 搜索用户, Space板块, 和内容
     *
     * GET /api/search?keyword=[keyword]&limitSpaceGuids=[guid,guid,]
     *
     * get.keyword 关键字
     *
     * get.limitSpaceGuids 当搜索指定板块时赋值:板块Space的Guid列表,每个guid以逗号','结尾
     *
     * get.scope 分类筛选: scope=all所有(默认), user用户, space板块, content内容
     *
     * @return array keyword:关键字, totals:搜索结果的各分类量(all所有, user用户, space板块, content内容数), results:搜索结果(mode:用于区分搜索结果类型=space板块、=user用户、=post内容, 不同的类型返回所对应的信息)
     */
    public function actionIndex(){
        $keyword = Yii::$app->request->get('keyword', "");
        $scope = Yii::$app->request->get('scope', "");
        $page = (int)Yii::$app->request->get('page', 1);
        $limitSpaceGuids = Yii::$app->request->get('limitSpaceGuids', "");

        $limitSpaces = array();
        if ($limitSpaceGuids !== "") {
            foreach (explode(",", $limitSpaceGuids) as $guid) {
                $guid = trim($guid);
                if ($guid != "") {
                    $space = Space::findOne(['guid' => trim($guid)]);
                    if ($space !== null) {
                        $limitSpaces[] = $space;
                    }
                }
            }
        }

        $options = [
            'page' => $page,
            'sort' => ($keyword == '') ? 'title' : null,
            //'pageSize' => Yii::$app->settings->get('paginationSize'),
            'pageSize' => 50,
            'limitSpaces' => $limitSpaces
        ];
        if ($scope == self::SCOPE_CONTENT) {
            $options['type'] = \humhub\modules\search\engine\Search::DOCUMENT_TYPE_CONTENT;
        } elseif ($scope == self::SCOPE_SPACE) {
            $options['model'] = Space::className();
        } elseif ($scope == self::SCOPE_USER) {
            $options['model'] = User::className();
        } else {
            $scope = self::SCOPE_ALL;
        }

        $searchResultSet = Yii::$app->search->find($keyword, $options);

        $pagination = new \yii\data\Pagination;
        $pagination->totalCount = $searchResultSet->total;
        $pagination->pageSize = $searchResultSet->pageSize;

        $datas = [];
        $results = $searchResultSet->getResultInstances();
        foreach ($results as $result){
            if ($result instanceof ContentActiveRecord || $result instanceof ContentContainerActiveRecord){
                //$result->getWallOut();
                //$d['id'] = $result->id;
                //if (!$underlyingObject instanceof \humhub\modules\post\models\Post){
                //if (!Yii::$app->controller instanceof ContentContainerController && $underlyingObject->content->container instanceof Space){
                //if($container instanceof User){
                //}
                if ($result instanceof \humhub\modules\post\models\Post){
                    $d = $this->getPost($result);
                }elseif ($result instanceof \humhub\modules\space\models\Space){
                    $d = $this->getSpace($result);
                }elseif ($result instanceof \humhub\modules\user\models\User){
                    $d = $this->getUser($result);
                }else{
                    continue;
                }
                //print_r($d);exit;
                $datas[] = $d;
            }else{
                //No Output for Class  get_class($result);
            }
        }

        return array(
            //'scope' => $scope,
            'keyword' => $keyword,
            'results' => $datas,
            //'pagination' => $pagination,
            'totals' => $this->getTotals($keyword, $options),
            'times'  => time(),
            //'limitSpaceGuids' => $limitSpaceGuids
        );
    }

    /**
     * 热搜关键词
     *
     * GET /api/search/hotword
     *
     * @return array 关键词列表
     */
    public function actionHotword(){
        $words = [
            '时尚',
            '学院',
            'U师',
        ];
        return $words;
    }

    /*
     * @inheritdoc
     */
    private function getUser($user){
        $uone['guid'] = $user->guid;
        $uone['profileimage'] = $user->getProfileImage()->getUrl();
        $uone['displayname'] = $user->displayName;
        $uone['title']   = $user->profile->title;
        $uone['follow']  = \humhub\modules\api\models\Follow::getFollow($user);
        $tags = [];
        foreach($user->getTags() AS $tag){
            $tags[] = $tag;
        }
        $uone['tags'] = $tags;
        $uone['u_v']  = $user->u_v;

        $x['user'] = $uone;
        $x['mode'] = 'user';
        return $x;
        return $uone;
    }
    /*
     * @inheritdoc
     */
    private function getSpace($space){
        $uone['guid'] = $space->guid;
        $uone['profileimage'] = $space->getProfileImage()->getUrl();
        $uone['description'] = $space->description;
        $uone['name'] = $space->name;
        $uone['s_v']  = $space->s_v;
        $uone['s_type']  = $space->s_type;
        //member
        $uone['ismember'] = 0;
        if ($space->isMember()) {
            $uone['ismember'] = 1;
        }
        //$tags = [];
        //foreach($space->getTags() AS $tag){
        //    $tags[] = $tag;
        //}
        //$uone['tags'] = $tags;

        $x['space'] = $uone;
        $x['mode'] = 'space';
        return $x;
        return $uone;
    }
    /*
     * @inheritdoc
     */
    private function getPost($wallEntry){

            $underlyingObject = $wallEntry->content->getPolymorphicRelation();

            if ($underlyingObject === null) {
                throw new Exception('Could not get contents underlying object!');
            }

            $underlyingObject->populateRelation('content', $wallEntry->content);

            //$output .= $this->controller->renderAjax('@humhub/modules/content/views/layouts/wallEntry', [
            //    'entry' => $wallEntry,
            //    'user' => $underlyingObject->content->user,
            //    'mode' => $this->mode,
            //    'object' => $underlyingObject,
            //    'content' => $underlyingObject->getWallOut()
            //        ], true);

            $_user = $underlyingObject->content->user;
            $user['guid'] = $_user->guid;
            $user['image'] = $_user->getProfileImage()->getUrl();
            $user['displayname'] = $_user->displayName;
            $user['title'] = $_user->profile->title;
            $user['follow']= \humhub\modules\api\models\Follow::getFollow($_user);

            //<!-- show profile name -->
            //if (!Yii::$app->controller instanceof ContentContainerController && $container instanceof User && $container->id != $user->id){
            //    $container->displayName;
            //}

            //<!-- show space name -->
            $space = [];
            if (!Yii::$app->controller instanceof ContentContainerController && $underlyingObject->content->container instanceof Space){
                $_space = $underlyingObject->content->container;
                $space['guid'] = $_space->guid;
                $space['name'] = $_space->name;
                $space['img'] = $_space->getProfileImage()->getUrl();
                //member
                $space['ismember'] = 0;
                if ($_space->isMember()) {
                    $space['ismember'] = 1;
                }
            }else{
                $space = (object)$space;
            }

            //Public Provate \humhub\modules\content\widgets\WallEntryLabels::widget(['object' => $object]);
            if ($underlyingObject->content->isSticked()){
                $o['label'] = 'Sticked';
            }
            if ($underlyingObject->content->isArchived()){
                $o['label'] = 'Archived';
            }
            if ($underlyingObject->content->isPublic()){
                $o['label'] = 'Public';
            }

            //content
            if (!$underlyingObject instanceof \humhub\modules\post\models\Post){
                $o['contentname'] = $underlyingObject->getContentName();
            }
            $o['id'] = $underlyingObject->id;
            //$o['message'] = $underlyingObject->getWallOut();
            //$o['message'] = $underlyingObject->message;
            $o['message'] = \humhub\widgets\RichText::widget(['text' => $underlyingObject->message, 'record' => $underlyingObject]);
            $o['created_at'] = $underlyingObject->created_at;
            $o['updated_at'] = $underlyingObject->updated_at;
            //Task
            $o['p_type'] = $underlyingObject->p_type;
            $o['p_team'] = $underlyingObject->p_team;
            $o['p_title']= \humhub\widgets\RichText::widget(['text' => $underlyingObject->p_title, 'record' => $underlyingObject]);
            //Video
            //$o['p_video']= $underlyingObject->p_video;
            $o['p_video'] = '';
            $_video = \humhub\modules\file\models\File::findOne(['guid' => $underlyingObject->p_video]);
            if( $_video ){ $o['p_video'] = $_video->getUrl(); }

            //Files
            if ($underlyingObject->isNewRecord && $underlyingObject->getRelation('content', false) !== null) {
                $files = \humhub\modules\file\models\File::findAll(['guid' => array_map('trim', explode(',', $underlyingObject->content->attachFileGuidsAfterSave))]);
            } else {
                $files = \humhub\modules\file\models\File::getFilesOfObject($underlyingObject);
            }
            $o['image'] = [];
            $o['files'] = [];
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image"){
                    $o['image'][] = $file->getPreviewImageUrl(200, 200);
                }
            }
            foreach ($files as $file){
                if ($file->getMimeBaseType() == "image")
                    continue;
                $f['url'] = $file->getUrl();
                $f['name'] = $file->file_name;
                $f['size'] = $file->size; //Yii::$app->formatter->asSize($file->size);
                $o['files'][] = $f;
            }



            //Comment
            //$o['comment'] = \humhub\modules\content\widgets\WallEntryAddons::widget(['object' => $underlyingObject]);
            //$o['comment'] = \humhub\modules\comment\widgets\Comments::widget(['object' => $underlyingObject]);
            $o['comment'] = \humhub\modules\api\cccstream\Comments::getLists($underlyingObject);

            //Like
            $o['like']    = \humhub\modules\api\cccstream\LikeLink::getLists($underlyingObject);

            //课程附加一个小节的视频 & 讲师
            if ( $underlyingObject->p_type == '2' ){
                //$episode = \humhub\modules\api\models\CourseEpisode::findOne(['season_id' => $underlyingObject->id]);
                //print_r($episode);exit;
                //if( $episode ){
                    $e['title']   = $underlyingObject->p_title; //$episode['title'];
                    $e['message'] = $underlyingObject->message; //$episode['message'];
                    $e['secs']    = $underlyingObject->p_secs;  //$episode['secs'];
                    $img = '';
                    $p_guid = md5('POST:'.$underlyingObject->id);
                    //$file = \humhub\modules\file\models\File::findOne(['guid' => $episode['imgguid']]);
                    $file = \humhub\modules\file\models\File::findOne(['guid' => $p_guid]);
                    if( $file ){
                        if ($file->getMimeBaseType() == "image"){
                            //$img = $file->getPreviewImageUrl(200, 200);
                            $img = $file->getUrl();
                        }
                    }
                    $e['image'] = $img;
                    //$e['video']   = $episode['video'];
                    $e['video'] = '';
                    $_video = \humhub\modules\file\models\File::findOne(['guid' => $underlyingObject->p_video]);
                    if( $_video ){
                        $e['video'] = $_video->getUrl();
                    }
                    $o['episodes'] = $e;

                    //讲师
                    //$t = json_decode($episode['teachers'], true);
                    $t = json_decode($underlyingObject->p_teachers, true);
                    if( isset( $t[0]) ){
                        $o['teachers'] = $t[0];
                    }else{
                        $o['teachers'] = (object)[];
                    }
                //}else{
                //    $o['episodes'] = (object)[];
                //    $o['teachers'] = (object)[];
                //}
            }


            //$wallOne['entry']  = $wallEntry; //table:wall_entry
            //$wallOne['mode'] = $this->mode;
            $wallOne['user'] = $user;
            $wallOne['space'] = $space;
            $wallOne['object'] = $o;

            $wallOne['mode'] = 'post';
            return $wallOne;
    }

    /*
     * @inheritdoc
     */
    protected function getTotals($keyword, $options){
        $totals = array();

        // Unset unnecessary search options
        unset($options['model']);
        unset($options['type']);
        unset($options['page']);
        unset($options['pageSize']);

        $searchResultSetCount = Yii::$app->search->find($keyword, array_merge($options, ['model' => User::className()]));
        $totals[self::SCOPE_USER] = $searchResultSetCount->total;
        $searchResultSetCount = Yii::$app->search->find($keyword, array_merge($options, ['model' => Space::className()]));
        $totals[self::SCOPE_SPACE] = $searchResultSetCount->total;

        $searchResultSetCount = Yii::$app->search->find($keyword, array_merge($options, ['type' => \humhub\modules\search\engine\Search::DOCUMENT_TYPE_CONTENT]));
        $totals[self::SCOPE_CONTENT] = $searchResultSetCount->total;
        $totals[self::SCOPE_ALL] = $totals[self::SCOPE_CONTENT] + $totals[self::SCOPE_SPACE] + $totals[self::SCOPE_USER];

        return $totals;
    }
}
